package com.moyu.crowdsource.service;

import com.aliyun.oss.OSSClient;
import com.moyu.crowdsource.entity.AccountUser;
import com.moyu.crowdsource.entity.AccountUserExample;
import com.moyu.crowdsource.entity.CommodityImage;
import com.moyu.crowdsource.mapperdao.AccountUserMapper;
import com.moyu.crowdsource.util.MyUUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

@Service
public class AccountUserService {

    @Autowired
    AccountUserMapper accountUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    OSSService ossService;

    public List<AccountUser> getAllAccount(){
        return accountUserMapper.selectByExample(null);
    }

    public  List<AccountUser> getAccountByAccountUsername(String accountUsername){
        AccountUserExample accountUserExample=new AccountUserExample();
        AccountUserExample.Criteria criteria=accountUserExample.createCriteria();
        criteria.andAccountUsernameEqualTo(accountUsername);
        return accountUserMapper.selectByExample(accountUserExample);
    }

    public boolean chackAccountUsername(String accountUsername){
        AccountUserExample accountUserExample=new AccountUserExample();
        AccountUserExample.Criteria criteria=accountUserExample.createCriteria();
        criteria.andAccountUsernameEqualTo(accountUsername);
        List<AccountUser> accountUsers=accountUserMapper.selectByExample(accountUserExample);
        if (!accountUsers.isEmpty()||null==accountUsers){
            return false;
        }else {
            return true;
        }
    }


    public void registerAccount(AccountUser accountUser){
        accountUser.setAccountPassword(passwordEncoder.encode(accountUser.getAccountPassword()));
        accountUserMapper.insertSelective(accountUser);
    }

    public void updateAccount(AccountUser accountUser){
        if (accountUser!=null&&accountUser.getAccountPassword()!=null&&accountUser.getAccountPassword()!=""){
            accountUser.setAccountPassword(passwordEncoder.encode(accountUser.getAccountPassword()));
        }
        accountUserMapper.updateByPrimaryKeySelective(accountUser);
    }

    public AccountUser getAccountInfo(Integer userId){
        return accountUserMapper.selectByPrimaryKey(userId);
    }


    public void uploadUserImage(File file, String filename, AccountUser accountUser) {

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(ossService.getEndpoint(), ossService.getAccessKeyId(),ossService.getAccessKeySecret());
        // 上传文件。

        ossClient.putObject(ossService.getBucketName(), ossService.getFirstkey() + filename, file);
        // 关闭Client。
        ossClient.shutdown();

        accountUser.setIconUrl(ossService.getUrlhead() +ossService.getFirstkey() + filename);
        updateAccount(accountUser);
    }
}
